<template>
	<div v-if="uploading" class="uploading">
		
	<el-button  :size="size" type="primary" >上传中{{ jd }}</el-button>
	</div>
	<el-upload
		v-else
		:action="$g.BASE_URL + 'admin/img/upload'"
		:show-file-list="false"
		:before-upload="beforeUpload"
		:on-progress="onProgress"
		:on-error="onError"
		:on-success="onSuccess"
		:http-request="httpRequest"
		accept="image/*"
	>
		<el-button :size="size" type="primary">点击上传</el-button>
	</el-upload>
</template>

<script>
import { $POST } from '@/puigins/request.js';
export default {
	props:{
		size:{
			type:String,
			default:"small"
		}
	},
	data() {
		return {
			uploading: false,
			jd: 0
		};
	},
	methods: {
		beforeUpload(file) {
			if(!file.type.startsWith('image/')){
				this.$message.warning("只能上传图片")
				return false
			}
			this.uploading=true
			return true;
		},
		onProgress(e) {
			this.jd=(e.loaded*100/e.total).toFixed(2)
		},
		onSuccess(res) {
			this.uploading=false
			if(res.code==200){
				this.$emit('success',res.data)
			}else{
				this.$msgError(res)
			}
		},
		onError(e) {
			this.uploading=false
			this.$message.error("上传失败")
			console.error(e)
		},
		httpRequest(config) {
			let name = config.filename;
			let file = config.file;
			let obj = {};
			Object.assign(obj, config.data);
			obj[name] = file;
			$POST(config.action, obj,config.onProgress)
				.then(config.onSuccess)
				.catch(config.onError);
		}
	}
};
</script>

<style lang="scss">
	
</style>
